package order

import (
	"context"
	"strconv"
	"time"

	"mall/common/globalkey"
	"mall/common/resultx"
	"mall/service/order/model"
	"mall/service/order/rpc/internal/svc"
	"mall/service/order/rpc/types/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type LogOrderReactionLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLogOrderReactionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LogOrderReactionLogic {
	return &LogOrderReactionLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LogOrderReactionLogic) LogOrderReaction(in *order.LogReactionReq) (*order.BaseIDResp, error) {
	if in.UserId == 0 {
		return nil, resultx.StatusError(resultx.USER_ID_INVALID, "")
	}

	if in.OrderId == 0 {
		return nil, resultx.NewErrCode(resultx.ORDER_ID_INVALID)
	}

	if len(in.Type) == 0 {
		return nil, resultx.StatusError(resultx.FORUM_REACTION_TYPE_INVALID, "")
	}

	var itemId uint64
	if in.OrderItemId != nil && *in.OrderItemId > 0 {
		itemId = *in.OrderItemId
	}
	var status uint8
	if in.Status != nil {
		status = uint8(*in.Status)
	} else {
		status = uint8(globalkey.StatusEnabled)
	}

	now := time.Now()
	date := now.Format("20060102")
	var createDate int
	if i, err := strconv.ParseInt(date, 10, 32); err == nil {
		createDate = int(i)
	}

	log := &model.OrderReactionLog{
		UserID:      in.UserId,
		OrderID:     in.OrderId,
		OrderItemID: itemId,
		Type:        in.Type,
		Status:      status,
		CreatedAt:   now,
		CreateDate:  createDate,
	}

	err := l.svcCtx.OrderReaction.Insert(l.ctx, nil, log)
	if err != nil {
		return nil, err
	}

	return &order.BaseIDResp{
		Id: log.LogID,
	}, nil
}
